"""
管理员API路由
"""
from typing import Optional, List
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from sqlalchemy import desc, func
from datetime import datetime, timedelta

from core.database import get_db
from api.auth import get_current_admin
from models.database import User, ParseTask, SliceTask, APILog, SystemConfig, SystemMetrics
from models.schemas import (
    UserResponse, UserCreate, UserUpdate, SystemConfigCreate, SystemConfigResponse,
    APILogResponse, BaseResponse, PaginatedResponse, LogStatsResponse
)
from core.auth import get_password_hash, verify_password
from core.config import get_settings
from core.logger import api_logger, log_api_call
from services.system_monitor import SystemMonitorService

router = APIRouter()
settings = get_settings()


@router.get("/users", response_model=PaginatedResponse)
@log_api_call
async def get_users(
    page: int = Query(1, ge=1),
    limit: int = Query(10, ge=1, le=100),
    role: Optional[str] = None,
    is_active: Optional[bool] = None,
    search: Optional[str] = None,
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """获取用户列表"""
    try:
        query = db.query(User)
        
        # 按角色筛选
        if role:
            query = query.filter(User.role == role)
        
        # 按状态筛选
        if is_active is not None:
            query = query.filter(User.is_active == is_active)
        
        # 搜索
        if search:
            query = query.filter(
                User.username.contains(search) | User.email.contains(search)
            )
        
        # 获取总数
        total = query.count()
        
        # 分页查询
        users = query.order_by(desc(User.created_at)).offset((page - 1) * limit).limit(limit).all()
        
        # 计算分页信息
        pages = (total + limit - 1) // limit
        
        return PaginatedResponse(
            items=[UserResponse.from_orm(user) for user in users],
            total=total,
            page=page,
            limit=limit,
            pages=pages
        )
        
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/users"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.post("/users", response_model=UserResponse)
@log_api_call
async def create_user(
    user_data: UserCreate,
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """创建用户"""
    try:
        # 检查用户名是否已存在
        if db.query(User).filter(User.username == user_data.username).first():
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Username already exists"
            )
        
        # 检查邮箱是否已存在
        if db.query(User).filter(User.email == user_data.email).first():
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Email already exists"
            )
        
        # 创建用户
        hashed_password = get_password_hash(user_data.password)
        db_user = User(
            username=user_data.username,
            email=user_data.email,
            password_hash=hashed_password,
            role=user_data.role
        )
        
        db.add(db_user)
        db.commit()
        db.refresh(db_user)
        
        api_logger.log_task_event("admin", "user_created", {
            "user_id": db_user.id,
            "username": db_user.username,
            "created_by": current_user.id
        })
        
        return UserResponse.from_orm(db_user)
        
    except HTTPException:
        raise
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/users"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.put("/users/{user_id}", response_model=UserResponse)
@log_api_call
async def update_user(
    user_id: int,
    user_data: UserUpdate,
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """更新用户"""
    try:
        user = db.query(User).filter(User.id == user_id).first()
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="User not found"
            )
        
        # 更新用户信息
        update_data = user_data.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(user, field, value)
        
        db.commit()
        db.refresh(user)
        
        api_logger.log_task_event("admin", "user_updated", {
            "user_id": user_id,
            "updated_by": current_user.id
        })
        
        return UserResponse.from_orm(user)
        
    except HTTPException:
        raise
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/users"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.delete("/users/{user_id}", response_model=BaseResponse)
@log_api_call
async def delete_user(
    user_id: int,
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """删除用户"""
    try:
        user = db.query(User).filter(User.id == user_id).first()
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="User not found"
            )
        
        # 不能删除自己
        if user_id == current_user.id:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Cannot delete yourself"
            )
        
        # 删除用户相关数据
        # 删除用户的解析任务
        parse_tasks = db.query(ParseTask).filter(ParseTask.user_id == user_id).all()
        for task in parse_tasks:
            # 这里可以添加删除相关文件的逻辑
            pass
        
        db.query(ParseTask).filter(ParseTask.user_id == user_id).delete()
        
        # 删除用户
        db.delete(user)
        db.commit()
        
        api_logger.log_task_event("admin", "user_deleted", {
            "user_id": user_id,
            "deleted_by": current_user.id
        })
        
        return BaseResponse(
            success=True,
            message="User deleted successfully"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/users"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.get("/tasks", response_model=PaginatedResponse)
@log_api_call
async def get_all_tasks(
    page: int = Query(1, ge=1),
    limit: int = Query(10, ge=1, le=100),
    status: Optional[str] = None,
    user_id: Optional[int] = None,
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """获取所有任务"""
    try:
        query = db.query(ParseTask)
        
        # 按状态筛选
        if status:
            query = query.filter(ParseTask.status == status)
        
        # 按用户筛选
        if user_id:
            query = query.filter(ParseTask.user_id == user_id)
        
        # 获取总数
        total = query.count()
        
        # 分页查询
        tasks = query.order_by(desc(ParseTask.created_at)).offset((page - 1) * limit).limit(limit).all()
        
        # 计算分页信息
        pages = (total + limit - 1) // limit
        
        return PaginatedResponse(
            items=tasks,
            total=total,
            page=page,
            limit=limit,
            pages=pages
        )
        
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/tasks"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.get("/logs", response_model=PaginatedResponse)
@log_api_call
async def get_api_logs(
    page: int = Query(1, ge=1),
    limit: int = Query(10, ge=1, le=100),
    user_id: Optional[int] = None,
    endpoint: Optional[str] = None,
    method: Optional[str] = None,
    status_code: Optional[int] = None,
    start_date: Optional[str] = Query(None),
    end_date: Optional[str] = Query(None),
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """获取API日志列表"""
    try:
        # 构建查询
        query = db.query(APILog)
        count_query = db.query(APILog)
        
        # 添加筛选条件
        if user_id:
            query = query.filter(APILog.user_id == user_id)
            count_query = count_query.filter(APILog.user_id == user_id)
        
        if endpoint:
            query = query.filter(APILog.endpoint.like(f"%{endpoint}%"))
            count_query = count_query.filter(APILog.endpoint.like(f"%{endpoint}%"))
        
        if method:
            query = query.filter(APILog.method == method)
            count_query = count_query.filter(APILog.method == method)
        
        if status_code:
            query = query.filter(APILog.status_code == status_code)
            count_query = count_query.filter(APILog.status_code == status_code)
        
        if start_date:
            try:
                start_datetime = datetime.strptime(start_date, "%Y-%m-%d")
                query = query.filter(APILog.created_at >= start_datetime)
                count_query = count_query.filter(APILog.created_at >= start_datetime)
            except ValueError:
                pass
        
        if end_date:
            try:
                end_datetime = datetime.strptime(end_date, "%Y-%m-%d")
                end_datetime = end_datetime.replace(hour=23, minute=59, second=59, microsecond=999999)
                query = query.filter(APILog.created_at <= end_datetime)
                count_query = count_query.filter(APILog.created_at <= end_datetime)
            except ValueError:
                pass
        
        # 获取总数
        total = count_query.count()
        pages = (total + limit - 1) // limit if total > 0 else 1
        
        # 分页查询
        logs = query.order_by(desc(APILog.created_at)).offset((page - 1) * limit).limit(limit).all()
        
        # 转换为响应格式
        log_responses = []
        for log in logs:
            log_response = APILogResponse(
                id=log.id,
                user_id=log.user_id,
                endpoint=log.endpoint,
                method=log.method,
                status_code=log.status_code,
                response_time=log.response_time,
                ip_address=log.ip_address,
                user_agent=log.user_agent,
                created_at=log.created_at
            )
            log_responses.append(log_response)
        
        return PaginatedResponse(
            items=log_responses,
            total=total,
            page=page,
            limit=limit,
            pages=pages
        )
        
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/logs"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.get("/users/stats")
@log_api_call
async def get_user_stats(
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """获取用户统计信息"""
    try:
        total_users = db.query(User).count()
        active_users = db.query(User).filter(User.is_active == True).count()
        admin_users = db.query(User).filter(User.role == "admin").count()
        
        # 今日新增用户
        today = datetime.now().date()
        today_users = db.query(User).filter(func.date(User.created_at) == today).count()
        
        # 用户任务统计
        user_task_counts = db.query(
            User.id,
            User.username,
            func.count(ParseTask.id).label('task_count')
        ).outerjoin(ParseTask, User.id == ParseTask.user_id)\
         .group_by(User.id, User.username).all()
        
        return {
            "total": total_users,
            "active": active_users,
            "admins": admin_users,
            "today": today_users,
            "user_task_counts": [
                {"user_id": user.id, "username": user.username, "task_count": user.task_count}
                for user in user_task_counts
            ]
        }
        
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/users/stats"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.get("/users/{user_id}", response_model=UserResponse)
@log_api_call
async def get_user_detail(
    user_id: int,
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """获取用户详情"""
    try:
        user = db.query(User).filter(User.id == user_id).first()
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="User not found"
            )
        
        return UserResponse.from_orm(user)
        
    except HTTPException:
        raise
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/users/detail"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.get("/logs/stats", response_model=LogStatsResponse)
@log_api_call
async def get_log_stats(
    start_date: Optional[str] = Query(None),
    end_date: Optional[str] = Query(None),
    method: Optional[str] = Query(None),
    status_code: Optional[int] = Query(None),
    endpoint: Optional[str] = Query(None),
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """获取日志统计信息"""
    try:
        # 构建基础查询
        logs = db.query(APILog)
        
        # 添加筛选条件
        if method:
            logs = logs.filter(APILog.method == method)
        
        if status_code:
            logs = logs.filter(APILog.status_code == status_code)
        
        if endpoint:
            logs = logs.filter(APILog.endpoint.like(f"%{endpoint}%"))
        
        # 添加日期筛选条件
        if start_date:
            try:
                start_datetime = datetime.strptime(start_date, "%Y-%m-%d")
                logs = logs.filter(APILog.created_at >= start_datetime)
            except ValueError:
                raise HTTPException(
                    status_code=400,
                    detail="开始日期格式错误，请使用YYYY-MM-DD格式"
                )
        
        if end_date:
            try:
                end_datetime = datetime.strptime(end_date, "%Y-%m-%d") + timedelta(days=1)
                logs = logs.filter(APILog.created_at < end_datetime)
            except ValueError:
                raise HTTPException(
                    status_code=400,
                    detail="结束日期格式错误，请使用YYYY-MM-DD格式"
                )
        
        # 获取所有日志记录
        all_logs = logs.all()
        
        # 计算统计信息
        total_requests = len(all_logs)
        success_count = sum(1 for log in all_logs if log.status_code < 400)
        error_count = sum(1 for log in all_logs if log.status_code >= 400)
        avg_response_time = sum(log.response_time for log in all_logs) / total_requests if total_requests > 0 else 0
        
        # 计算成功率
        success_rate = (success_count / total_requests * 100) if total_requests > 0 else 0
        
        return LogStatsResponse(
            total_requests=total_requests,
            success_rate=round(success_rate, 2),
            avg_response_time=round(avg_response_time, 3),
            error_count=error_count
        )
        
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/logs/stats"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.get("/logs/export")
@log_api_call
async def export_logs(
    start_date: Optional[datetime] = Query(None),
    end_date: Optional[datetime] = Query(None),
    method: Optional[str] = Query(None),
    status: Optional[int] = Query(None),
    search: Optional[str] = Query(None),
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """导出日志"""
    try:
        from fastapi.responses import StreamingResponse
        import csv
        import io
        
        # 构建查询
        query = db.query(APILog)
        
        # 按日期筛选
        if start_date:
            query = query.filter(APILog.created_at >= start_date)
        if end_date:
            query = query.filter(APILog.created_at <= end_date)
        
        # 按方法筛选
        if method:
            query = query.filter(APILog.method == method)
        
        # 按状态码筛选
        if status:
            query = query.filter(APILog.status_code == status)
        
        # 搜索
        if search:
            query = query.filter(
                APILog.path.contains(search) | 
                APILog.user_agent.contains(search)
            )
        
        # 获取所有日志
        logs = query.order_by(desc(APILog.created_at)).all()
        
        # 创建CSV内容
        output = io.StringIO()
        writer = csv.writer(output)
        
        # 写入表头
        writer.writerow([
            'ID', '时间', '方法', '路径', '状态码', '响应时间(ms)', '用户代理', 'IP地址'
        ])
        
        # 写入数据
        for log in logs:
            writer.writerow([
                log.id,
                log.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                log.method,
                log.path,
                log.status_code,
                log.response_time,
                log.user_agent,
                log.ip_address
            ])
        
        # 创建响应
        output.seek(0)
        return StreamingResponse(
            iter([output.getvalue()]),
            media_type="text/csv",
            headers={"Content-Disposition": "attachment; filename=logs.csv"}
        )
        
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/logs/export"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.get("/logs/{log_id}")
@log_api_call
async def get_log_detail(
    log_id: int,
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """获取日志详情"""
    try:
        log = db.query(APILog).filter(APILog.id == log_id).first()
        if not log:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Log not found"
            )
        
        return APILogResponse.from_orm(log)
        
    except HTTPException:
        raise
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/logs/detail"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.get("/settings")
@log_api_call
async def get_settings(
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """获取系统设置"""
    try:
        # 从环境变量和配置中获取设置
        config_dict = {}
        
        # 从SystemConfig表中获取配置
        configs = db.query(SystemConfig).all()
        for config in configs:
            config_dict[config.config_key] = config.config_value
        
        # 如果没有配置，使用默认值
        if not config_dict:
            config_dict = {
                "app_name": settings.app_name,
                "app_version": settings.app_version,
                "host": settings.host,
                "port": settings.port,
                "debug": settings.debug,
                "jwt_secret_key": settings.jwt_secret_key,
                "jwt_expire_seconds": settings.jwt_expire_seconds,
                "cors_origins": settings.cors_origins,
                "rate_limit_requests": settings.rate_limit_requests,
                "rate_limit_window": settings.rate_limit_window,
                "upload_dir": settings.upload_dir,
                "max_file_size": settings.max_file_size,
                "allowed_extensions": list(settings.allowed_extensions),
                "parsed_results_dir": settings.parsed_results_dir,
                "results_retention_days": settings.results_retention_days,
                "max_concurrent_tasks": settings.max_concurrent_tasks,
                "task_timeout_seconds": settings.task_timeout_seconds,
                "mineru_model_path": settings.mineru_model_path,
                "mineru_device": settings.mineru_device,
                "default_ocr_engine": settings.default_ocr_engine,
                "log_level": settings.log_level,
                "log_file": settings.log_file,
                "redis_url": settings.redis_url
            }
        
        return config_dict
        
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/settings"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.put("/settings")
@log_api_call
async def update_settings(
    settings_data: dict,
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """更新系统设置"""
    try:
        for key, value in settings_data.items():
            # 查找现有配置
            config = db.query(SystemConfig).filter(SystemConfig.config_key == key).first()
            
            if config:
                # 更新现有配置
                config.config_value = str(value)
                config.updated_at = datetime.now()
            else:
                # 创建新配置
                config = SystemConfig(
                    config_key=key,
                    config_value=str(value),
                    description=f"Setting for {key}"
                )
                db.add(config)
        
        db.commit()
        
        api_logger.log_task_event("admin", "settings_updated", {
            "updated_by": current_user.id,
            "keys": list(settings_data.keys())
        })
        
        return {"success": True, "message": "Settings updated successfully"}
        
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/settings"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.get("/settings/export")
@log_api_call
async def export_settings(
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """导出配置"""
    try:
        configs = db.query(SystemConfig).all()
        
        config_dict = {}
        for config in configs:
            config_dict[config.config_key] = config.config_value
        
        return config_dict
        
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/settings/export"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.post("/system/restart")
@log_api_call
async def restart_system(
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """重启系统"""
    try:
        # 这里应该实现重启逻辑
        # 由于这是Web应用，重启可能需要外部服务管理器
        
        api_logger.log_task_event("admin", "system_restart", {
            "initiated_by": current_user.id
        })
        
        return {"success": True, "message": "System restart initiated"}
        
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/system/restart"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.post("/system/clear-cache")
@log_api_call
async def clear_cache(
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """清理缓存"""
    try:
        # 这里应该实现缓存清理逻辑
        # 可以清理Redis缓存、文件缓存等
        
        api_logger.log_task_event("admin", "cache_cleared", {
            "initiated_by": current_user.id
        })
        
        return {"success": True, "message": "Cache cleared successfully"}
        
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/system/clear-cache"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.post("/system/cleanup-results")
@log_api_call
async def cleanup_old_results(
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """清理过期结果"""
    try:
        import os
        import shutil
        from datetime import datetime, timedelta
        
        # 计算过期时间
        retention_days = settings.results_retention_days
        cutoff_date = datetime.now() - timedelta(days=retention_days)
        
        # 查找过期的解析结果
        old_results = db.query(ParseResult).filter(
            ParseResult.created_at < cutoff_date
        ).all()
        
        # 删除过期结果文件
        for result in old_results:
            if result.file_path and os.path.exists(result.file_path):
                try:
                    os.remove(result.file_path)
                except:
                    pass
        
        # 删除数据库记录
        db.query(ParseResult).filter(ParseResult.created_at < cutoff_date).delete()
        db.commit()
        
        api_logger.log_task_event("admin", "old_results_cleaned", {
            "initiated_by": current_user.id,
            "cleaned_count": len(old_results)
        })
        
        return {"success": True, "message": f"Cleaned {len(old_results)} old results"}
        
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/system/cleanup-results"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.get("/stats")
@log_api_call
async def get_system_stats(
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """获取系统统计信息"""
    try:
        # 用户统计
        total_users = db.query(User).count()
        active_users = db.query(User).filter(User.is_active == True).count()
        admin_users = db.query(User).filter(User.role == "admin").count()
        
        # 任务统计
        total_tasks = db.query(ParseTask).count()
        completed_tasks = db.query(ParseTask).filter(ParseTask.status == "completed").count()
        failed_tasks = db.query(ParseTask).filter(ParseTask.status == "failed").count()
        processing_tasks = db.query(ParseTask).filter(ParseTask.status == "processing").count()
        
        # 今日统计
        today = datetime.now().date()
        today_users = db.query(User).filter(func.date(User.created_at) == today).count()
        today_tasks = db.query(ParseTask).filter(func.date(ParseTask.created_at) == today).count()
        
        # 近7天统计
        week_ago = datetime.now() - timedelta(days=7)
        week_tasks = db.query(ParseTask).filter(ParseTask.created_at >= week_ago).count()
        
        # 文件类型统计
        file_type_stats = {}
        all_tasks = db.query(ParseTask).all()
        for task in all_tasks:
            ext = task.filename.split('.')[-1].lower() if '.' in task.filename else 'unknown'
            file_type_stats[ext] = file_type_stats.get(ext, 0) + 1
        
        # 用户活跃度统计
        active_users_7days = db.query(User).filter(
            User.last_login >= week_ago
        ).count()
        
        return {
            "users": {
                "total": total_users,
                "active": active_users,
                "admins": admin_users,
                "today": today_users,
                "active_7days": active_users_7days
            },
            "tasks": {
                "total": total_tasks,
                "completed": completed_tasks,
                "failed": failed_tasks,
                "processing": processing_tasks,
                "today": today_tasks,
                "last_7days": week_tasks,
                "success_rate": (completed_tasks / total_tasks * 100) if total_tasks > 0 else 0
            },
            "file_types": file_type_stats
        }
        
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/stats"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.get("/configs", response_model=List[SystemConfigResponse])
@log_api_call
async def get_system_configs(
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """获取系统配置"""
    try:
        configs = db.query(SystemConfig).all()
        return [SystemConfigResponse.from_orm(config) for config in configs]
        
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/configs"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.post("/configs", response_model=SystemConfigResponse)
@log_api_call
async def create_system_config(
    config_data: SystemConfigCreate,
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """创建系统配置"""
    try:
        # 检查配置键是否已存在
        if db.query(SystemConfig).filter(SystemConfig.config_key == config_data.config_key).first():
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Config key already exists"
            )
        
        config = SystemConfig(
            config_key=config_data.config_key,
            config_value=config_data.config_value,
            description=config_data.description
        )
        
        db.add(config)
        db.commit()
        db.refresh(config)
        
        api_logger.log_task_event("admin", "config_created", {
            "config_key": config.config_key,
            "created_by": current_user.id
        })
        
        return SystemConfigResponse.from_orm(config)
        
    except HTTPException:
        raise
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/configs"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.put("/configs/{config_id}", response_model=SystemConfigResponse)
@log_api_call
async def update_system_config(
    config_id: int,
    config_data: SystemConfigCreate,
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """更新系统配置"""
    try:
        config = db.query(SystemConfig).filter(SystemConfig.id == config_id).first()
        if not config:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Config not found"
            )
        
        # 更新配置
        config.config_key = config_data.config_key
        config.config_value = config_data.config_value
        config.description = config_data.description
        config.updated_at = datetime.now()
        
        db.commit()
        db.refresh(config)
        
        api_logger.log_task_event("admin", "config_updated", {
            "config_key": config.config_key,
            "updated_by": current_user.id
        })
        
        return SystemConfigResponse.from_orm(config)
        
    except HTTPException:
        raise
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/configs"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.delete("/configs/{config_id}", response_model=BaseResponse)
@log_api_call
async def delete_system_config(
    config_id: int,
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """删除系统配置"""
    try:
        config = db.query(SystemConfig).filter(SystemConfig.id == config_id).first()
        if not config:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Config not found"
            )
        
        db.delete(config)
        db.commit()
        
        api_logger.log_task_event("admin", "config_deleted", {
            "config_key": config.config_key,
            "deleted_by": current_user.id
        })
        
        return BaseResponse(
            success=True,
            message="Config deleted successfully"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/configs"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


# 系统监控API
@router.get("/system/metrics")
@log_api_call
async def get_system_metrics(
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """获取当前系统监控指标"""
    try:
        metrics = SystemMonitorService.get_cached_metrics()
        return {
            "cpu_percent": metrics["cpu_percent"],
            "memory_percent": metrics["memory_percent"],
            "memory_used": metrics["memory_used"],
            "memory_total": metrics["memory_total"],
            "disk_percent": metrics["disk_percent"],
            "disk_used": metrics["disk_used"],
            "disk_total": metrics["disk_total"],
            "load_average": metrics["load_average"],
            "uptime": metrics["uptime"],
            "status": SystemMonitorService.get_system_status(),
            "formatted_uptime": SystemMonitorService.format_uptime(metrics["uptime"]),
            "timestamp": metrics["timestamp"].isoformat()
        }
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/system/metrics"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.get("/system/metrics/history")
@log_api_call
async def get_system_metrics_history(
    hours: int = Query(24, ge=1, le=168),  # 1小时到1周
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """获取系统监控历史数据"""
    try:
        history = SystemMonitorService.get_metrics_history(hours)
        return {
            "hours": hours,
            "data": history
        }
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/system/metrics/history"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.post("/system/cleanup-metrics")
@log_api_call
async def cleanup_system_metrics(
    days: int = Query(7, ge=1, le=30),  # 1天到30天
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """清理系统监控历史数据"""
    try:
        SystemMonitorService.cleanup_old_metrics(days)
        return {"success": True, "message": f"Cleaned metrics older than {days} days"}
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/admin/system/cleanup-metrics"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


# 导出路由器
admin_router = router